package edu.stanford.junction.tictactoe;

/**
 * The board on which play is currently occurring
 * @author David Kettler
 * @author Steve Recio
 */
public class Board {
	
	private int[][] boardArray;
	
	public static final int empty_slot = 0;
	public static final int player_x = 1;
	public static final int player_o = 2;
	public static final int stalemate = 3;
	
	/**
	 * makes and zeroes a new 3x3 board
	 */
	public Board() {
		boardArray = new int[3][3];
		zeroBoard();
	}
	
	private void zeroBoard() {
		for (int i = 0; i < 3; i++)
			for (int j = 0; j < 3; j++)
				boardArray[i][j] = empty_slot;
	}
	
	/**
	 * @param player Board.player_x for X, Board.player_o for O
	 * @param row the row you wish to play in (0, 1, or 2)
	 * @param col the column you wish to play in (0, 1, or 2)
	 */
	public void makeMove(int player, int row, int col) {
		boardArray[row][col] = player;
	}
	
	/**
	 * @return true if board is full, false if there is an empty slot
	 */
	private boolean boardIsFull() {
		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 3; j++) {
				if (boardArray[i][j] == empty_slot)
					return false;
			}
		}
		
		return true;
	}
	
	/**
	 * @return Board.player_x if X won game, Board.player_o if O won game,
	 * Board.empty_slot if board not full, and Board.stalemate on stalemate
	 */
	public int checkGameStatus() {
		for (int i = 0; i < 3; i++) {
			if (boardArray[i][0] == boardArray[i][1] && boardArray[i][1] == boardArray[i][2])
				return boardArray[i][0];
		}
		
		for (int j = 0; j < 3; j++) {
			if (boardArray[0][j] == boardArray[1][j] && boardArray[1][j] == boardArray[2][j])
				return boardArray[0][j];
		}
		
		if (boardArray[0][0] == boardArray[1][1] && boardArray[1][1] == boardArray[2][2])
			return boardArray[0][0];
		
		if (boardArray[2][0] == boardArray[1][1] && boardArray[1][1] == boardArray[0][2])
			return boardArray[2][0];
		
		if (boardIsFull())
			return 3;
		
		return 0;
	}
	
	/**
	 * @param row the row you wish to check (0, 1, or 2)
	 * @param col the column you wish to check (0, 1, or 2)
	 * @return Board.player_x if X, Board.player_o if O, Board.empty_slot if slot empty
	 */
	public int getCell(int row, int col) {
		return boardArray[row][col];
	}
}
